function ECsidebarRefresh_step2() {
	ECSidebarUpdateURL(document.getElementById('urlbar').value);
}

function ECSidebarUpdateURL(url) {
	var block = document.getElementById('sidebar').contentDocument.getElementById('ECSidebar_url');
	block.removeChild(block.firstChild);
	block.appendChild(document.createTextNode(url));
	var comments = new CommentList(url);
	comments.inject2dom('ECSidebar_comments');
}

function ECsidebarRefresh() {//call this to refresh the sidebar
	var sidebar = top.document.getElementById("sidebar");
	sidebar.contentWindow.addEventListener("DOMContentLoaded", ECsidebarRefresh_step2, false);
}

function ECSidebarShow() {
	toggleSidebar('ECSidebar_view');
	ECsidebarRefresh();

	// give ourselves access to the tab windows 
	var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
				.getInterface(Components.interfaces.nsIWebNavigation)
                   		.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                   		.rootTreeItem
                   		.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   		.getInterface(Components.interfaces.nsIDOMWindow);

	var tab = mainWindow.getBrowser().addTab("about:blank");

	// Add listener for tab changed
	var container = window.gBrowser.mPanelContainer;
	container.addEventListener("select", ECSidebarTabChanged, false);

	mainWindow.getBrowser().removeTab(tab);
}

var ECSidebarCurrentTab = null;

function ECSidebarTabChanged(event) {
	var browser = window.gBrowser.getBrowserAtIndex(window.gBrowser.mTabContainer.selectedIndex);

	if(ECSidebarCurrentTab){
		ECSidebarCurrentTab.removeProgressListener(ECSidebarURLListener);
	}

	var block = document.getElementById('sidebar').contentDocument.getElementById('ECSidebar_url');
	
	//new url loader thingy..
	browser.addProgressListener(ECSidebarURLListener, Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);

	ECSidebarCurrentTab = browser;
	ECSidebarUpdateURL(browser.currentURI.spec);
}

var ECSidebarURLListener= {
	QueryInterface: function(aIID){
		if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
		    aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
	 	    aIID.equals(Components.interfaces.nsISupports))
			return this;

		throw Components.results.NS_NOINTERFACE;
	},

  	onLocationChange: function(aProgress, aRequest, aURI){
		ECSidebarUpdateURL(aURI.spec);
	},

	onStateChange: function() {},
	onProgressChange: function() {},
	onStatusChange: function() {},
	onSecurityChange: function() {},
	onLinkIconAvailable: function() {}
};

function Comment(content, user,date, nUrl){
	this.content=content;	//This is the text of the comment
	this.user=user;		//This is the name of the user that created this. Plaintext?
	this.date=date;		//This could be a string representing a time, preferably using the Date.toString() method, and then that can be used to make a new Date object... which makes calculations easier
	this.url=nUrl;		//I guess another string.
	//By the way... I've included this because it's in the first definition, but I don't think it needs to be here anymore, seeing how each comment object should only ever be accessed from a comment list, and comment lists are URL specific anyway.
	this.toString=CommentToString;	//This would make it really easy to output the comment
}

/*
CommentToString: Implementation of the toString element for the comment object
	Just outputs the comment in a friendly form. Feel free to change what the output looks like.
*/
function CommentToString(){
	return "<"+this.user+"> "+this.content;
}


function CommentList(url){
	//Set up the class. Everything here's a method besides comment.
	this.fetch=CommentListFetch;	//Fills comment with the comments from the given URL
	this.save=CommentListSave;	//Saves the current comment list to wherever (Locally for now)
	this.comment=[];	//An array of comment objects, which are defined above
	this.add=CommentListAdd;	//Adds a comment to the comment list
	this.remove=CommentListRemove;	//Removes a comment (Tricky security issues, who can remove what)
	this.inject2dom = CommentListDOM;

	//Now for the actual construction
	this.fetch(url);	//Fill the List with the comments for the given URL
}

/*
CommentListDOM: Implementation of the inject2dom method of the CommentList class.
	Takes the id of a DOM node and injects comments.
*/
function CommentListDOM(id) {
	var block = document.getElementById('sidebar').contentDocument.getElementById(id);
	while (block.firstChild) {
		block.removeChild(block.firstChild);
	}
	var node;
	for(var i in this.comment) {
		node = document.createElement('label');
		node.appendChild(document.createTextNode(this.comment[i].toString()));
		block.appendChild(node);
	}
}

/*
CommentListAdd: Implementation for the add method of the CommentList class.
	Takes in a Comment object and adds it to the CommentList.
	This does not save it, it only adds it to the temporary copy.
	For a local thing, this could be dumb, but for a server maybe not.
	Maybe all comments could be saved in an onUnLoad event or something...

	nComment should be a comment Object.
	Technically you won't get an error if it isn't, not until you try to use it later at least. The magic of javascript.
*/
function CommentListAdd(nComment){
	this.comment.push(nComment);
}

/*
CommentListRemove: Should remove an item from the local list, but I don't know what to do here
	Physically removing the item from the array isn't tough, but there are things that need to be sorted out before this method can be implemented

	Actaully, I don't even know what toRemove is. Is it a comment object to search the aray for an remove?
	Is it an integer index to remove?
	Is it the string content to search for?
	Is it Steve Jobs? Torvalds? Vivaldi?
*/
function CommentListRemove(toRemove){
	
}

/*
GetPrefs: This just returns the preferences manager object so that it can be used...
*/
function GetPrefs(){
	//This beast is the interface for the about:config thing. That bit is ugly, but it works out well in the end.
	return Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
}

/*
CommentListFetch: This function, in this version, reads the preferences pane (about:config) and decodes the data to fill the comment array with comments related to this url.

	I want to make it clear, this url is not used as a URL. It is not where the data is read from or anything. It is just to tell the fetch function which URL's comments to load.

	Without talking to anyone I've decided that each website will have it's own config entry of the form:
		extensions.eComments.<URL>
	with all of the characters that the URL contains.

	If this poses a problem later, I'm sure it can be changed

	then each commentList will be saved as a list in the form
		"<" username, date, url, content ">" "<" ... and so on.
	I've put content at the end so that it'll be easier to figure out the commas, so we don't get screwed up by that.

	I think usernames should not be able to have comments in them. 
	Neither usernames or comments should be able to have "<",">" characters, that'll just make it a mess to parse. 
*/

function CommentListFetch(url){
	//alert("Fetch?");
	var prefManager=GetPrefs();	//This is the preferences object
	try{
		var PrefString=prefManager.getCharPref("extensions.eComments."+url);
	}catch(err){
		//alert("Exception!");
		
		//If I'm here, then the PrefString doesn't exist yet. Sets the string to empty so it'll break out later...
		Temp="";
	}
	//alert("Got Prefs");
	if(PrefString=="") return;
	
	var Temp=PrefString.split("<");	//I think this is an abuse of type-less-ness
	
	for(var i=1;i< Temp.length;i++){	//Start at 1 becasue the first item is the blank space before the first "<"
		var comma=Temp[i].indexOf(",",0);	//Holds the location of the first comma
		var user=Temp[i].substring(0,comma);

		var comma2=Temp[i].indexOf(",",comma+1);
		var date=Temp[i].substring(comma+1,comma2);

		var comma3=Temp[i].indexOf(",",comma2+1);
		var nUrl=Temp[i].substring(comma2+1,comma3);

		var end=Temp[i].lastIndexOf(">");
		var content=Temp[i].substring(comma3+1,end);

		this.add(new Comment(content,user,date,nUrl));
	}
}

/*
CommentListSave: Kind of does the opposite of the above function. Makes the current commentlist into a weird list and saves it
*/
function CommentListSave(url){
	//alert("Saving!");
	var prefManager=GetPrefs();
	var Temp="";
	for(var i=0; i < this.comment.length; i++){
		Temp+="<"+this.comment[i].user+","+this.comment[i].date+","+this.comment[i].url+","+this.comment[i].content+"> ";
	}
	prefManager.setCharPref("extensions.eComments."+url,Temp);
	//alert("Saved!");
}
